package com.wumai.keystrokes.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wumai.keystrokes.models.settings.KeyConfig;
import com.wumai.keystrokes.models.settings.KeyGroup;
import net.minecraftforge.fml.loading.FMLPaths;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * @author trick12138
 * @date 2025-08-20
 */
public class JsonStorage {
    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
    private static final Path CONFIG_DIR = FMLPaths.CONFIGDIR.get().resolve("keystrokes");
    private static final Path KEY_GROUPS_DIR = CONFIG_DIR.resolve("keygroups");
    static final Path RESOURCES_DIR = CONFIG_DIR.resolve("resources");

    public static KeyConfig loadConfig() {
        KeyConfig config = null;
        
        // 确保配置目录存在
        if (!Files.exists(CONFIG_DIR)) {
            try {
                Files.createDirectories(CONFIG_DIR);
            } catch (IOException e) {
                e.printStackTrace();
                return config;
            }
        }
        
        // 确保按键组目录存在
        if (!Files.exists(KEY_GROUPS_DIR)) {
            try {
                Files.createDirectories(KEY_GROUPS_DIR);
            } catch (IOException e) {
                e.printStackTrace();
                return config;
            }
        }

        // 确保资源目录存在
        if (!Files.exists(RESOURCES_DIR)) {
            try {
                Files.createDirectories(RESOURCES_DIR);
            } catch (IOException e) {
                e.printStackTrace();
                return config;
            }
        }
        
        // 检查配置目录下是否存在.json文件
        File[] configFiles = CONFIG_DIR.toFile().listFiles((dir, name) -> name.endsWith(".json"));
        boolean hasConfigFiles = configFiles != null && configFiles.length > 0;
        
        // 如果没有.json配置文件，则创建默认配置
        if (!hasConfigFiles) {
            File defaultConfigFile = CONFIG_DIR.resolve("default.json").toFile();
            return config;
        }
        
        // 重新检查并读取所有配置文件，返回第一个有效的配置
        configFiles = CONFIG_DIR.toFile().listFiles((dir, name) -> name.endsWith(".json"));
        if (configFiles != null && configFiles.length > 0) {
            for (File file : configFiles) {
                try (Reader reader = new FileReader(file)) {
                    KeyConfig loadedConfig = GSON.fromJson(reader, KeyConfig.class);
                    // 返回第一个有效的配置文件
                    if (loadedConfig != null) {
                        return loadedConfig;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return config;
    }
    
    public static List<KeyGroup> loadKeyGroups() {
        List<KeyGroup> keyGroups = new ArrayList<>();
        
        // 确保按键组目录存在
        if (!Files.exists(KEY_GROUPS_DIR)) {
            try {
                Files.createDirectories(KEY_GROUPS_DIR);
            } catch (IOException e) {
                e.printStackTrace();
                return keyGroups;
            }
        }
        
        // 读取所有按键组文件
        File[] files = KEY_GROUPS_DIR.toFile().listFiles((dir, name) -> name.endsWith(".json"));
        if (files != null) {
            for (File file : files) {
                try (Reader reader = new FileReader(file)) {
                    KeyGroup group = GSON.fromJson(reader, KeyGroup.class);
                    keyGroups.add(group);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return keyGroups;
    }
    
    public static void saveConfig(KeyConfig config, List<KeyGroup> keyGroups) {
        if (!Files.exists(CONFIG_DIR)) {
            try {
                Files.createDirectories(CONFIG_DIR);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
        
        File configFile = CONFIG_DIR.resolve(config.getFileName() + ".json").toFile();
        try (Writer writer = new FileWriter(configFile)) {
            GSON.toJson(config, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        saveKeyGroups(keyGroups);
    }
    
    private static void saveKeyGroups(List<KeyGroup> keyGroups) {
        if (!Files.exists(KEY_GROUPS_DIR)) {
            try {
                Files.createDirectories(KEY_GROUPS_DIR);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
        
        // 先清理旧的按键组文件
        File[] existingFiles = KEY_GROUPS_DIR.toFile().listFiles();
        if (existingFiles != null) {
            for (File file : existingFiles) {
                file.delete();
            }
        }
        
        // 保存每个按键组到单独的文件
        for (int i = 0; i < keyGroups.size(); i++) {
            KeyGroup group = keyGroups.get(i);
            File groupFile = KEY_GROUPS_DIR.resolve("group_" + i + ".json").toFile();
            try (Writer writer = new FileWriter(groupFile)) {
                GSON.toJson(group, writer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}